import 'dart:async';

import 'package:flutter_repository/annotations/repository.dart';
import 'package:flutter_repository/repository/request_state.dart';
import 'package:get/get.dart';
import 'package:example_app/widgets/request_retry_dialog.dart';

class Repo extends Repository {
  const Repo()
      : super(
            streamWrapper: MyWrapper.customStreamWrapper,
            futureWrapper: MyWrapper.customFutureWrapper);
}

///Repository的代理方法
///处理异常和资源状态
class MyWrapper {
  //流的方式
  static Stream<Resource<T>> customStreamWrapper<T>(
      Stream<Resource<T>> Function() function,
      {bool retry = false}) async* {
    yield Resource.loading();
    try {
      var result = function.call();
      await for (var data in result) {
        yield data;
      }
    } catch (e) {
      //重试代码
      if (retry) {
        var toRetry = await Get.dialog(const RequestRetryDialog());
        if (toRetry == true) {
          yield* customStreamWrapper(function, retry: retry);
        } else {
          yield Resource.failed(e);
        }
      } else {
        yield Resource.failed(e);
      }
    }
  }

  //异步的方式
  static Future<Resource<T>> customFutureWrapper<T>(
      FutureOr<Resource<T>> Function() function,
      {bool retry = false}) async {
    try {
      var result = function.call();
      if (result is Future) {
        var _result = await result;
        return _result;
      }
      return result;
    } catch (e) {
      //重试代码
      if (retry) {
        var toRetry = await Get.dialog(const RequestRetryDialog());
        if (toRetry == true) {
          return await customFutureWrapper(function, retry: retry);
        }
      }
      return Resource.failed(e);
    }
  }
}
